import hashlib
import hmac
import secrets
from datetime import datetime, timedelta, timezone
import jwt
from typing import Optional

class SecurityManager:
    def __init__(self, secret_key: str = None):
        self.secret_key = secret_key or secrets.token_hex(32)
        self.token_expiry = timedelta(hours=24)
    
    def generate_api_token(self, user_id: str, permissions: list) -> str:
        """生成API令牌"""
        current_time = datetime.now(timezone.utc)
        
        payload = {
            'user_id': user_id,
            'permissions': permissions,
            'exp': current_time + self.token_expiry,
            'iat': current_time
        }
        return jwt.encode(payload, self.secret_key, algorithm='HS256')
    
    def verify_api_token(self, token: str) -> Optional[dict]:
        """验证API令牌"""
        try:
            payload = jwt.decode(token, self.secret_key, algorithms=['HS256'])
            return payload
        except jwt.ExpiredSignatureError:
            return None
        except jwt.InvalidTokenError:
            return None
    
    def hash_sensitive_data(self, data: str) -> str:
        """哈希敏感数据"""
        return hashlib.sha256(data.encode()).hexdigest()
    
    def validate_input(self, input_data: str, max_length: int = 1000) -> bool:
        """验证输入数据"""
        if not input_data or len(input_data) > max_length:
            return False
        
        # 检查是否有潜在的危险字符
        dangerous_patterns = ['<script>', 'javascript:', 'onload=']
        for pattern in dangerous_patterns:
            if pattern in input_data.lower():
                return False
        
        return True
    
    def sanitize_api_key(self, api_key: str) -> str:
        """清理API密钥输入"""
        return api_key.strip().replace(' ', '')